/*漫画唯一标识*/
let name_id = '';
/*浏览器临时存储 倒序 数据*/
let chapters_desc = [];
/*每次加载的 篇章 页数*/
let strip_asc = 0;
/*每次加载的 篇章 条数*/
const page_asc = 30;
/*浏览器临时存储 正序 数据*/
let chapters_asc = [];
/*正序 或 倒序*/
let asc_desc = 'desc';
/*篇章 加载 按钮*/
let clike = `<div style="margin-top: 50px;"  id="loadClick" onclick="loadClick()">加载更多....</div>`;
/*篇章 提示盒子*/
let div = $("#null-Warning");
/*篇章 盒子*/
let chapte_div = $(".article-2-1");
/*评论 最大字数*/
const text_leng = 450;
/*评论 页数*/
let strip = 0;
/*评论 页数*/
let comment_strip = 0;
/*评论 每次查询条数*/
const page = 20;
/*评论数据 盒子*/
let comment_box = $(".comment-box");
let comment_click_box = $("#comment-click");
/*评论 本地存储*/
let comment_data = [];


/*阅读*/
let co_read = () => {
    reading(name_id);
    if (asc_desc === 'desc') {
        location.href = "/manhua/look/picture/" + chapters_desc[0].nameId + "/" + chapters_desc[0].nameOrder;
    } else {
        location.href = "/manhua/look/picture/" + chapters_asc[0].nameId + "/" + chapters_asc[0].nameOrder;
    }
    ;
};

/*阅读*/
let reading = (id) => {
    let config = {
        url: voer_url.prefix + '/' + voer_url.rea,
        type: "POST",
        dataType: "json",
        data: {id: id},
    };
    $.ajax(config)

}

/*评论查询*/
$("#comment-navigation").click(function () {
    if (comment_data.length != 0) {
        comment_box.empty();
        for (let i = classify_status.zero, len = comment_data.length; i < len; i++) {
            comment_box.append(comment_html(comment_data[i]));
        }
        return;
    }
    let navigation = $("#comment-navigation").text();
    let numder = navigation.substring(0, navigation.indexOf("评论"));
    /*等于o条评论 就没有必要查询了*/
    if (numder === '0') {
        comment_box.html(`<div style="width: 100%;height: 100px;line-height: 100px;text-align: center;color: #999c9e;">还没有评论你是第一个呦，快来评论吧...</div>`)
        return;
    }
    comment_post({nameId: name_id, strip: comment_strip, page: page});
});

/*点击下一页 评论*/
let comment_click = () => {
    comment_post({nameId: name_id, strip: comment_strip, page: page});
}

/*评论请求*/
let comment_post = (data) => {
    $.operate.request(voer_url.prefix + '/' + voer_url.comm, data, function (row) {
        /*关闭遮罩层*/
        $.modal.closeLoading();
        if (row.code === web_status.SUCCESS) {
            let list = row.data;
            if (list != null && list != '') {

                comment_box.append(comment_html(list));

                if (list.length < 20) {
                    comment_click_box.html('<span>快写下你喜欢的评论吧^_^...</span>');
                } else {
                    comment_click_box.html('<a onclick="comment_click()">加载更多..</a>');
                }
                /*评论 页*/
                comment_strip++;

                comment_data.push(list);
            } else {
                comment_click_box.html('<span>没有评论了，快写下你喜欢的评论吧^_^...</span>');
            }
        } else {
            $.modal.alertError(row.msg);
        }
    })
}
/*打开 或 关闭 每条评论 二级评论框*/
let reply = (reply) => {
    let id = reply.substring(reply.lastIndexOf("-") + 1);

    let i = $("#comment-span-" + id + "");
    /*关闭评论 盒子*/
    $("#comment-" + id + "").slideUp("slow");
    if ('fa fa-angle-down' != i.attr("class")) {
        i.attr("class", "fa fa-angle-down");
    }
    /*打开或关闭*/
    $("#" + reply + "").slideToggle("slow");

}

/*打开 或 关闭 每条一级评论 二级评论*/
let comment = (comment) => {
    let span = $("#" + comment + "");
    let id = comment.substring(comment.lastIndexOf("-") + 1);
    let i = $("#comment-span-" + id + "");
    /*关闭 填写框*/
    $("#reply-" + id + "").slideUp("slow");

    if ('fa fa-angle-down' === i.attr("class")) {
        i.attr("class", "fa fa-angle-up");
    } else {
        i.attr("class", "fa fa-angle-down");
    }
    /*打开或关闭*/
    span.slideToggle("slow");

}

/*评论点赞*/
function give(id) {
    let numder = $("#article-2-2-right-give-" + id + "");
    let data = {id: id, numder: numder.text()};
    $.operate.request(voer_url.prefix + '/' + voer_url.gi, data, function (row) {
        /*关闭遮罩层*/
        $.modal.closeLoading();
        if (row.code === web_status.SUCCESS) {
            let giv = parseInt(numder.text());
            numder.text(++giv);
        } else {
            $.modal.alertWarning(row.msg);
        }
    });
}


/*一级二级 添加成功 拼接数据*/
let Level1 = (data) => {

    let html = `<div class="article-2-2">
                            <div class="article-2-2-left">
                                <img src="${data.head}" alt="头像">
                            </div>
                            <div class="article-2-2-right">
                                <p class="article-2-2-right-name">${data.userName}</p>
                                <p class="article-2-2-right-time">${data.createTime}</p>
                                <p class="article-2-2-right-text">${data.remark}</p>
                                <p class="article-2-2-right-give"><span id="article-2-2-right-give-${data.id}">${data.give}</span>&emsp;<i
                                        class="fa fa-thumbs-o-up" style="cursor: pointer;" onclick="give(${data.id})"></i></p>
                                <p style="clear: both;">
                                    <span class="article-2-2-right-reply" onclick="reply('reply-${data.id}')">回复</span>.&emsp;

                                 <span class="article-2-2-right-strip">0：条数回复&nbsp;</span></p>


                                <div class="article-2-2-right-article-2-2-comment" id="reply-${data.id}">
                                    <label class="col-sm-5 control-label">回复：</label>
                                    <div class="col-sm-12">`;

    if (data.type === '3' || data.type === '2') {
        html += `<textarea type="text" name="textarea-3-text-${data.id}" class="form-control"
                                                  placeholder="填写想要的评论吧。"></textarea>
                                                  <a class="btn btn-w-m btn-info article-2-2-comment-cilcka" onclick="textareaClick3(${data.id},${data.superior})">评论</a>`;
    } else {
        html += `<textarea type="text" name="textarea-text-${data.id}" class="form-control"
                                              placeholder="填写想要的评论吧。"></textarea>
                                              <a class="btn btn-w-m btn-info article-2-2-comment-cilcka" onclick="textareaClick(${data.id})">评论</a>`;
    }

    html += `</div></div>`;
    html += `<div class="none-last" id="comment-${data.id}"></div>`;

    return html;
}
/*一级添加评论*/
$("#textarea-click").click(function () {
    let text = $("textarea[name='textarea-text']");
    if (text.val().length > text_leng) {
        $.modal.alertError('评论最多可填写' + text_leng + '个字符...');
        return;
    }
    if (text.val() === '' || text.val() == null) {
        $.modal.alertError('评论不能是空...');
        return;
    }
    commentadd({nameId: name_id, text: text.val(), id: voer_status.zero, type: '1'}, voer_status.num);
});

/*二级评论 数据提交*/
function textareaClick(id) {
    let text = $("textarea[name='textarea-text-" + id + "']");
    if (text.val().length > text_leng) {
        $.modal.alertError('评论最多可填写' + text_leng + '个字符...');
        return;
    }
    if (text.val() === '' || text.val() == null) {
        $.modal.alertError('评论不能是空...');
        return;
    }
    commentadd({nameId: name_id, text: text.val(), id: id, type: '2'}, voer_status.min_dataNumber_ini);
}

/*三级评论 数据提交*/
let textareaClick3 = (jid, listid) => {
    let text = $("textarea[name='textarea-3-text-" + jid + "']");
    if (text.val().length > text_leng) {
        $.modal.alertError('评论最多可填写' + text_leng + '个字符...');
        return;
    }
    if (text.val() === '' || text.val() == null) {
        $.modal.alertError('评论不能是空...');
        return;
    }
    let data = {nameId: name_id, text: text.val(), id: jid, type: '3'};
    $.operate.request(voer_url.prefix + '/' + voer_url.comm_add, data, function (row) {
        /*关闭遮罩层*/
        $.modal.closeLoading();
        if (row.code === web_status.SUCCESS) {
            let data_data = row.data;
            if (data_data != null) {
                $("textarea").val("");
                let src = $(".right-img>img").attr("src");
                /*三级回复者 二级名称*/
                let name = $("#article-3-right-name-" + data.id + "").text();
                /*评论数据*/
                let text = $("#article-3-right-text-" + data.id + "").text();

                data_data.remark = data.text + "//@" + name + ":" + text;

                $("#comment-" + listid + "").prepend(Level1(data_data));
                $.modal.msgSuccess('成功！..');
            } else {
                $.modal.alertWarning('添加失败！');
            }
        } else {
            $.modal.alertWarning(row.msg);
        }
    })
}
/*添加评论*/
let commentadd = (data, leve) => {
    $.operate.request(voer_url.prefix + '/' + voer_url.comm_add, data, function (row) {
        /*关闭遮罩层*/
        $.modal.closeLoading();
        if (row.code === web_status.SUCCESS) {
            let data_data = row.data;
            if (data_data != null) {
                $("textarea").val("");
                let src = $(".right-img>img").attr("src");
                if (leve === voer_status.num) {
                    /*一级*/
                    if ($(".comment-box>div").text() === '还没有评论你是第一个呦，快来评论吧...') {
                        comment_box.html(Level1(data_data));
                    } else {
                        comment_box.prepend(Level1(data_data));
                    }
                } else if (leve === voer_status.min_dataNumber_ini) {
                    /*二级*/
                    comment('comment-' + data.id + '');
                    $("#comment-" + data.id + "").prepend(Level1(data_data));
                }
                $.modal.msgSuccess('成功！..');
            } else {
                $.modal.alertWarning('添加失败！');
            }
        } else {
            $.modal.alertWarning(row.msg);
        }
    })
}
/*时间*/
Date.prototype.Format = function (fmt) { // author: meizz
    var o = {
        "M+": this.getMonth() + 1, // 月份
        "d+": this.getDate(), // 日
        "h+": this.getHours(), // 小时
        "m+": this.getMinutes(), // 分
        "s+": this.getSeconds(), // 秒
        "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
        "S": this.getMilliseconds() // 毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
/*收藏*/
$("#collect").click(function () {
    $.operate.request(voer_url.prefix + '/' + voer_url.coll, {id: name_id}, function (row) {
        $.modal.closeLoading();
        if (row.code === web_status.SUCCESS) {
            let collect = $("#collect");
            if (collect.text() === '★ 已收藏') {
                collect.text('☆ 收藏')
            } else {
                collect.text('★ 已收藏')
            }
        } else if (row.code === web_status.FAIL) {
            $.modal.alertWarning(row.msg);
        }
    });
})

/*加载更多*/
function loadClick() {
    let data = {nameId: name_id, order: asc_desc, strip: voer_status.num, page: page_asc};
    $.operate.request(voer_url.prefix + '/' + voer_url.order_url, data, function (row) {
        /*关闭遮罩层*/
        $.modal.closeLoading();
        if (row.code === web_status.SUCCESS) {
            chapte_div.append(data_desc_asc(row.data));
            div.text('全部篇章...');
        } else {
            $.modal.alertWarning(row.msg);
        }
    });
}

/*漫画篇章数据 本地保存 倒序 正序*/
let data_desc_asc = (list) => {
    let html = '';
    for (let i = voer_status.zero, len = list.length; i < len; i++) {
        /*添加*/
        if (asc_desc === 'desc') {
            chapters_desc.push(list[i]);
        } else {
            chapters_asc.push(list[i]);
        }
        let name = list[i].name;
        if ($(document.body).width() > 700) {
            if (name.length > 9) {
                name = name.substring(0, 9) + "..";
            }
        }
        html += `<div>
                          <a href="/manhua/look/picture/${list[i].nameId}/${list[i].nameOrder}" onclick="reading(${name_id})" target="_blank">${name}</a>
                      </div>`;
    }
    return html;
}
/*漫画篇章 不本地保存*/
let chapters = (list) => {
    let html = '';
    for (let i = voer_status.zero, len = list.length; i < len; i++) {

        let name = list[i].name;
        if ($(document.body).width() > 700) {
            if (name.length > 9) {
                name = name.substring(0, 9) + "..";
            }
        }
        html += `<div>
                          <a href="/manhua/look/picture/${list[i].nameId}/${list[i].nameOrder}" onclick="reading(${name_id})" target="_blank">${name}</a>
                     </div>`;
    }
    return html;
}
/*正序 倒序*/
let order = (str) => {
    let left = $(".switchover-left");
    let right = $(".switchover-right");
    /*本漫画数据丢失...*/
    if (div.text() === '本漫画数据丢失^_^...') {
        $.modal.alertWarning('本漫画数据丢失^_^...');
        return;
    }
    if (str === 'desc') {
        asc_desc = 'desc';
        right.css({background: '#ffffff'})
        left.css({background: '#F7F9FA'})
        desc(str);
    } else {
        asc_desc = 'asc';
        left.css({background: '#ffffff'})
        right.css({background: '#F7F9FA'})
        asc(str);
    }
}
/*倒序 业务逻辑*/
let desc = (str) => {
    if (chapters_desc.length === page_asc) {
        div.html(clike);
    } else {
        div.html('全部篇章...');
    }
    chapte_div.html(chapters(chapters_desc));
}
/*正序 逻辑*/
let asc = (str) => {
    if (chapters_asc.length == 0) {
        let data = {nameId: name_id, order: str, strip: strip_asc, page: page_asc};
        $.operate.request(voer_url.prefix + '/' + voer_url.order_url, data, function (row) {
            /*关闭遮罩层*/
            $.modal.closeLoading();
            if (row.code === web_status.SUCCESS) {
                let numder = row.data.length;
                chapte_div.html(data_desc_asc(row.data));
                if (numder == 0) {
                    div.text('本漫画数据丢失...');
                } else if (numder < page_asc) {
                    div.text('全部篇章...');
                } else {
                    div.html(clike);
                }
                return
            } else {
                $.modal.alertWarning(row.msg);
            }
        });
    } else if (chapters_asc.length === page_asc) {
        div.html(clike);
    } else {
        div.html('全部篇章...');
    }
    chapte_div.html(chapters(chapters_asc));
}


/*漫画基本数据*/
let manhua = (data) => {
    let not = '无';
    let complete = '完结';
    let null_str = null;
    $("meta[itemprop='url']").attr("content", $.haHa.decode(data.theCover))
    $("meta[itemprop='image']").attr("content", $.haHa.decode(data.theCover))

    /*名称*/
    $("#name").text(data.name != null_str ? data.name : not);
    /*作者*/
    $("#author").text(data.author != null_str ? data.author : not);
    /*状态*/
    $("#newZhang").text(data.newZhang == '0' ? complete : '连载中');
    /*类型*/
    $("#countriesName").text(data.countriesName != null_str ? data.countriesName : not);
    /*更新时间*/
    $("#updateTime").text(data.updateTime != null_str ? data.updateTime : not);
    /*最新*/
    $("#newest").text(data.newZhang == '0' ? complete : data.newZhang);
    /*介绍*/
    $("#introduce").text(data.remark != null_str ? data.remark : not);
    /*图片*/
    $("#theCover").attr({
        'src': data.theCover != null_str ? $.haHa.decode(data.theCover) : '',
        'alt': data.name != null_str ? data.name : not
    });
}
/*推荐*/
let recommend = (list) => {
    let html = '';
    for (let i = classify_status.zero, len = list.length; i < len; i++) {

        let newZhang = list[i].newZhang;

        if (newZhang.length > voer_status.eijht) {
            newZhang = newZhang.substring(voer_status.zero, voer_status.eijht) + "..";
        }

        let name = list[i].name;

        if (name.length > voer_status.eijht) {
            name = name.substring(voer_status.zero, voer_status.eijht) + "..";
        }

        html += ` <div class="articl-1-2-box">
                                    <a href="/manhua/look/over/${list[i].id}">
                                        <img src="${$.haHa.decode(list[i].theCover)}" alt="${list[i].name}" onerror="$.common.errorimg(this)">
                                        <div >
                                            <span class="articl-1-2-box-left">${newZhang}</span>
                                        </div>
                                        <span>${name}</span>
                                    </a>
                       </div>`;

    }
    return html;

}

/*评论 查询 拼装数据*/
let comment_html = (list) => {
    let html = '';
    for (let i = classify_status.zero, len = list.length; i < len; i++) {
        html += `<div class="article-2-2">
                            <div class="article-2-2-left">
                                <img src="${list[i].head}" alt="头像">
                            </div>
                            <div class="article-2-2-right">
                                <p class="article-2-2-right-name">${list[i].userName}</p>
                                <p class="article-2-2-right-time">${list[i].createTime}</p>
                                <p class="article-2-2-right-text">${list[i].remark}</p>
                                <p class="article-2-2-right-give"><span id="article-2-2-right-give-${list[i].id}">${list[i].give}</span>&emsp;<i
                                        class="fa fa-thumbs-o-up" style="cursor: pointer;" onclick="give(${list[i].id})"></i></p>
                                <p style="clear: both;">
                                    <span class="article-2-2-right-reply" onclick="reply('reply-${list[i].id}')">回复</span>.&emsp;`

        if (list[i].mhComment != null) {
            html += `<span class="article-2-2-right-strip" onclick="comment('comment-${list[i].id}')">${list[i].mhComment.length}：条数回复&nbsp;<i class="fa fa-angle-down" onclick="comment('comment-${list[i].id}')" id="comment-span-${list[i].id}"></i></span></p>`
            /*<i class="fa fa-angle-up"></i> 向上箭头*/
        } else {
            html += `<span class="article-2-2-right-strip">0：条数回复&nbsp;</span></p>`
        }

        html += `<div class="article-2-2-right-article-2-2-comment" id="reply-${list[i].id}">
                                    <label class="col-sm-5 control-label">回复：</label>
                                    <div class="col-sm-12">
                                    <textarea type="text" name="textarea-text-${list[i].id}" class="form-control"
                                              placeholder="填写想要的评论吧。"></textarea>
                                        <a class="btn btn-w-m btn-info article-2-2-comment-cilcka" onclick="textareaClick(${list[i].id})">评论</a>
                                    </div>
                       </div>`;

        html += `<div class="none-last" id="comment-${list[i].id}">`;

        if (list[i].mhComment != null) {
            for (let j = classify_status.zero, len = list[i].mhComment.length; j < len; j++) {
                html += `<div class="article-2-2">
                                    <div class="article-2-2-left ">
                                        <img src="${list[i].mhComment[j].head}" alt="头像">
                                    </div>
                                    <div class="article-2-2-right">
                                        <p class="article-2-2-right-name" id="article-3-right-name-${list[i].mhComment[j].id}">${list[i].mhComment[j].userName}</p>
                                        <p class="article-2-2-right-time">${list[i].mhComment[j].createTime}</p>
                                        <p class="article-2-2-right-text" id="article-3-right-text-${list[i].mhComment[j].id}">${list[i].mhComment[j].remark.replace("//@", "<span style='color: red;'>//@<span>")}</p>
                                        <p class="article-2-2-right-give"><span id="article-2-2-right-give-${list[i].mhComment[j].id}">${list[i].mhComment[j].give}</span>&emsp;<i
                                                class="fa fa-thumbs-o-up" style="cursor: pointer;" onclick="give(${list[i].mhComment[j].id})"></i></p>
                                     <p style="clear: both;">
                                            <span class="article-2-2-right-reply" onclick="reply('reply-${list[i].mhComment[j].id}')">回复</span>.&emsp;
                                        </p>
                                        <div class="article-2-2-right-article-2-2-comment" id="reply-${list[i].mhComment[j].id}">
                                           <label class="col-sm-5 control-label">回复：</label>
                                           <div class="col-sm-12">
                                               <textarea type="text" name="textarea-3-text-${list[i].mhComment[j].id}" class="form-control"
                                                  placeholder="填写想要的评论吧。"></textarea>
                                               <a class="btn btn-w-m btn-info article-2-2-comment-cilcka" onclick="textareaClick3(${list[i].mhComment[j].id},${list[i].id})">评论</a>
                                           </div>
                                        </div>
                              </div>
                              </div>`;
            }
            html += '</div>';
        } else {
            html += `<div class="none-last" id="comment-${list[i].id}"></div>`;
        }

        html += ' </div></div>';
    }
    return html;
}
